package org.example.demo.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.example.demo.constant.HintConstant;
import org.example.demo.entity.InformationHint;
import org.example.demo.entity.TalkInformation;
import org.example.demo.entity.User;
import org.example.demo.service.InformationHintService;
import org.example.demo.service.TalkInformationService;
import org.example.demo.service.UserService;
import org.example.demo.util.AjaxResult;
import org.example.demo.util.ReturnMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("talk")
public class TalkInformationController {

    @Resource
    private TalkInformationService talkInformationService;

    @Resource
    private UserService userService;


    @Autowired
    private InformationHintService informationHintService;

    // 分页查询谈话信息列表
    @PostMapping("selectPage")
    public AjaxResult selectPage(@RequestBody TalkInformation talkInfo,
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize) {
        // ReturnMap returnMap = new ReturnMap();
        Page<TalkInformation> page = new Page<>(pageNum, pageSize);
        Map<String, Object> map = new HashMap<>();

        List<TalkInformation> informations = talkInformationService.list();

        // 收集所有用户
        Map<Long, User> userMap = userService.list(new QueryWrapper<User>()
                .lambda()
                .like(talkInfo.getNickName() != null && !talkInfo.getNickName().isEmpty(), User::getName,
                        talkInfo.getNickName()))
                .stream()
                .collect(Collectors.toMap(User::getId, user -> user));
        if (!userMap.isEmpty()) {
            // 批量查询用户信息
            QueryWrapper<TalkInformation> queryUserWrapper = new QueryWrapper<>();
            queryUserWrapper.lambda().in(TalkInformation::getUserId, userMap.keySet())
                    .orderByDesc(TalkInformation::getCreateTime) // 查询条件
                    .like(talkInfo.getTalkTitle() != null && !talkInfo.getTalkTitle().isEmpty(), TalkInformation::getTalkTitle,
                    talkInfo.getTalkTitle()); // 查询条件h


            Page<TalkInformation> result = talkInformationService.page(page, queryUserWrapper);
            // 遍历结果集，设置用户昵称
            for (TalkInformation record : result.getRecords()) {
                User user = userMap.get(record.getUserId());
                if (user != null) {
                    record.setNickName(user.getName());
                }
            }

            map.put("page", result);
            // returnMap.setData("page", result);
        } else {
            map.put("page", new ArrayList<>());
            // returnMap.setData("page", new ArrayList<>());
        }

        return AjaxResult.success(map);
    }

    // 查询谈话信息总数
    @PostMapping("selectCount")
    public AjaxResult selectCount(@RequestBody TalkInformation talkInfo) {
        // ReturnMap returnMap = new ReturnMap();
        Map<String, Object> map = new HashMap<>();
        // 收集所有用户
        Map<Long, User> userMap = userService
                .list(new QueryWrapper<User>().lambda().like(
                        talkInfo.getNickName() != null && !talkInfo.getNickName().isEmpty(), User::getName,
                        talkInfo.getNickName()))
                .stream()
                .collect(Collectors.toMap(User::getId, user -> user));
        if (!userMap.isEmpty()) {
            QueryWrapper<TalkInformation> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda()
                    .in(TalkInformation::getUserId, userMap.keySet())
                    .eq(talkInfo.getApplicantId() != null,
                            TalkInformation::getApplicantId, talkInfo.getApplicantId());

            int count = talkInformationService.count(queryWrapper);

            map.put("count", count);
            // returnMap.setData("count", count);
        } else {
            map.put("count", 0);
            // returnMap.setData("count", 0);
        }

        return AjaxResult.success(map);
        // return returnMap.getreturnMap();
    }

    // 新增/修改谈话信息
    @PostMapping("saveOrUpdate")
    public AjaxResult saveOrUpdate(@RequestBody TalkInformation talkInfo) {
        // ReturnMap returnMap = new ReturnMap();
        // Map<String, Object> map = new HashMap<>();

        if (talkInfo.getId() != null) {
            talkInformationService.updateById(talkInfo);
        } else {
            talkInfo.setCreateTime(LocalDateTime.now());
            talkInformationService.save(talkInfo);


            // 把谈话记录放入消息提示表中
            InformationHint informationHint = InformationHint.builder()
                    .userId(talkInfo.getUserId())
                    .title(HintConstant.TALK_HINT)
                    .content(talkInfo.getTalkTitle())
                    .time(talkInfo.getTalkTime())
                    .build();
//            System.out.println(talkInfo.getTalkType());
            informationHintService.save(informationHint);
        }

        // returnMap.setReturnCode(200);
        return AjaxResult.success();
    }

    // 查询谈话信息详情
    @GetMapping("detail")
    public AjaxResult detail(@RequestParam Integer id) {
        // ReturnMap returnMap = new ReturnMap();
        TalkInformation talkInfo = talkInformationService.getById(id); // 把id传给talkInformationService，
        // 并接收传递过来的谈话信息记录
        Long userId = talkInfo.getUserId();
        User user = userService.getById(userId);
        talkInfo.setNickName(user.getName());

        Map<String, Object> map = new HashMap<>();
        map.put("talkInfo", talkInfo);
        // returnMap.setData("talkInfo", talkInfo);
        return AjaxResult.success(map);
    }

    // 删除谈话信息
    @DeleteMapping("delete")
    public AjaxResult delete(@RequestParam Integer id) {
        boolean success = talkInformationService.removeById(id);

        if (success)
            return AjaxResult.success();
        return AjaxResult.error();

    }

    @PostMapping("selectAllUser")
    public AjaxResult selectAllUser() {

        Map<String, Object> map = new HashMap<>();
        map.put("data", userService.list(new QueryWrapper<User>().lambda().eq(User::getRole, "用户")));
        return AjaxResult.success(map);
    }

    /**
     * 根据userId返回谈话信息
     * @param userId
     * @return
     */
    @GetMapping("/selectByUserId/{userId}")
    public AjaxResult selectByUserId(@PathVariable Long userId) {


        // 条件筛选
        QueryWrapper wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId);
        List list = talkInformationService.list(wrapper);

        Map<String, Object> map = new HashMap<>();
        map.put("data", list);

        return AjaxResult.success(map);
    }
}